<template>
  <div v-loading="loading" class="dynamic-container">
    <el-table
      v-if="accountListData && accountListData.length"
      :data="accountListData"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      header-cell-class-name="dynamic-edit-table-cell"
      border
      fit
      hightlight-current-row
    >
      <el-table-column
        v-if="showSerial"
        align="left"
        label="序号"
        width="50">
        <template slot="header" slot-scope="scope">
          <div class="dynamic-table-header">
            <span class="label">{{ scope.column.label }}</span>
          </div>
        </template>
        <template slot-scope="scope">
          <div style="padding-left:12px;">{{ (page-1)*perPage+scope.$index +1 }}</div>
        </template>
      </el-table-column>
      <template v-for="(settingItem, index) in listSetting">
        <el-table-column
          :key="index"
          :label="settingItem.label"
          v-bind="settingItem.prop || {}"
          :width="settingItem.width || '100px'"
          align="left">
          <template slot="header" slot-scope="scope">
            <div class="dynamic-table-header">
              <span v-if="settingItem.isRequired" style="color: #f56c6c;margin-right:4px;">*</span>
              <span class="label">{{ scope.column.label }}</span>
            </div>
          </template>
          <template slot-scope="scope">
            <!-- 编辑模式 -->
            <div v-if="scope.row._isEdit || scope.row._isAdd" >
              <!-- 输入框：字符串 -->
              <template v-if="settingItem.type === 'inputText'">
                <el-input
                  v-model="scope.row[settingItem.keyword]"
                  :disabled="settingItem.disabled"
                  :maxlength="settingItem.maxlength || 50"
                  :placeholder="settingItem.placeholder || settingItem.label"
                  size="small"
                  type="text"
                  clearable
                />
              </template>
              <!-- 输入框：数字 -->
              <div v-if="settingItem.type === 'inputNumber'" style="position:relative;">
                <el-input
                  v-model="scope.row[settingItem.keyword]"
                  :placeholder="settingItem.placeholder || settingItem.label"
                  :disabled="settingItem.disabled"
                  :oninput="`if(value>${settingItem.maxnumber || 999999999999})value=${settingItem.maxnumber || 999999999999}`"
                  type="number"
                  size="small"
                  @change="numberInputChange(scope.row, settingItem.keyword)"
                  @mousewheel.native.prevent
                />
              </div>
              <!-- 城市级联选择 -->
              <three-level-area
                v-if="settingItem.type === 'selectCity'"
                :select-type="settingItem.selectType || 'region'"
                :selected-options="handelArr(scope.row[settingItem.keyword])"
                @update:options="threeLevelArea($event, scope.row, settingItem.keyword)" />
              <!-- 下拉选项 -->
              <selectWithoutHttp
                v-if="settingItem.type === 'select'"
                v-model="scope.row[settingItem.keyword]"
                :list-data="settingItem.options || []"
                :multiple="false"
                :key-name="settingItem.keyName ? settingItem.keyName : 'id'"
                :label-name="settingItem.labelName ? settingItem.labelName : 'name'"
                filterable
                clearable
              />
              <div v-if="settingItem.type === 'text'">
                <ToolTip :content="scope.row[settingItem.keyword]" />
              </div>
            </div>
            <!-- 只读模式 -->
            <div v-else :style="settingItem.showType==='price'?{justifyContent: 'flex-end'}:''" class="read-content">
              <PriceColumn v-if="settingItem.showType==='price'" :real-val="scope.row[settingItem.keyword]" :price="scope.row[settingItem.keyword]" />
              <span v-else-if="settingItem.type === 'datepicker'">{{ scope.row[settingItem.keyword] | format('YYYY/MM/DD') }}</span>
              <span v-else-if="settingItem.renderType === 'filter'">{{ dataFilter(scope.row[settingItem.keyword], settingItem) }}</span>
              <span v-else-if="settingItem.type === 'select' && settingItem.keyword !== 'bank'">{{ selectFilter(scope.row[settingItem.keyword], settingItem) }}</span>
              <template v-else>
                <ToolTip :content="scope.row[settingItem.renderKeyword] || scope.row[settingItem.keyword]" />
              </template>
            </div>
          </template>
        </el-table-column>
      </template>
      <el-table-column
        :width="100"
        align="left"
        label="操作"
        fixed="right">
        <template slot-scope="scope">
          <div style="display:flex; align-items:center">
            <template v-if="scope.row._isEdit || scope.row._isAdd">
              <el-button type="text" @click="save(scope.row, scope.$index)"><span style="font-size:14px;">保存</span></el-button>
              <div class="line"/>
              <el-button type="text" @click="beCancle(scope.row, scope.$index)"><span style="font-size:14px;">取消</span></el-button>
            </template>
            <template v-else>
              <el-button type="text" @click="editItem(scope.row)"><span style="font-size:14px;">编辑</span></el-button>
              <div class="line"/>
              <el-button type="text" @click="deleteItem(scope.row, scope.$index)"><span style="font-size:14px;">删除</span></el-button>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <empty-placeholder v-else style="margin-bottom: 24px"/>
    <div v-if="accountData.total > 10" style="margin-top:12px;display:flex;">
      <span style="flex:1"/>
      <el-pagination
        :page-sizes="[10, 50, 100, 250, 500]"
        :current-page="page"
        :page-size="perPage"
        :total="accountData.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
  </div>
</template>

<script>
/**
 * 动态编辑表格：listSetting的属性说明
 *
 * @param {string}  label   名称
 * @param {string}  keyword 字段
 * @param {string}  width   宽度
 * @param {Boolean}  isRequired   必填
 * @param {string}  type    编辑状态时的类型：inputText(字符串输入框)、inputNumber(数字输入框)、select(不能下拉加载的下拉框)
 * @param {array}  options  下拉选项
 * @param {string}  renderType  只读模式渲染内容方式：filter(根据options列表渲染名称)
 */

import emptyIcon from '@/assets/empty-invoice.png';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import ThreeLevelArea from '@/components/ThreeLevelArea';
import emptyDataIcon from '@/assets/empty-data-icon.png';
import emptyPlaceholder from '@/components/Common/emptyPlaceholder';
import Title from '@/components/Title';
import { format } from '@/filters/date';
// api
import { accountEdit, accountDelete, accountList, accountAdd } from '@/api/supplier';
// import { getDepartmentAll } from '@/api/config';
import { accountType } from '@/components/SupplierComponent/supplierManageComp/data';
import accountTable from '@/mixins/accountTable';

export default {
  components: { Title, selectWithoutHttp, selectWithUserLoad, ThreeLevelArea, emptyPlaceholder },
  filters: { format },
  mixins: [accountTable],
  props: {
    type: {
      type: Number,
      default: 1
    },
    supplierId: {
      type: Number,
      default: 0
    },
    showSerial: {
      type: Boolean,
      default: true
    },
    defaultParams: {
      type: Object,
      default: () => {
        return {};
      }
    },
    disableValidKeys: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      emptyDataIcon,
      loading: false,
      page: 1,
      perPage: 10,
      emptyIcon,
      accountData: {},
      accountListData: [] // 收款账户列表
    };
  },
  computed: {
    listSetting() {
      accountType.forEach(el => {
        if (el.keyword === 'bank') {
          el.options = this.bankList;
        }
        if (el.keyword === 'payPlatform') {
          el.options = this.paymentList;
        }
      });
      return accountType;
    }
  },
  created() {
    this.getAccountList();
    this.getBankList();
    this.getPaymentList();
  },
  methods: {
    dataFilter(rowData, settingItem) {
      if ((rowData || rowData === 0) && settingItem && settingItem.options) {
        const obj = settingItem.options.find(i => Number(i.id) === Number(rowData));
        return obj ? obj.name : '--';
      }
      return '--';
    },
    selectFilter(rowData, settingItem) {
      if ((rowData || rowData === 0) && settingItem && settingItem.options) {
        const obj = settingItem.options.find(i => Number(i.value) === Number(rowData));
        return obj ? obj.label : '--';
      }
      return '--';
    },
    numberInputChange(row, key) {
      if (row[key]) row[key] = Number(row[key]).toFixed(2);
    },
    hasAdd() {
      let hasAdd = false;
      this.accountListData.forEach((el) => {
        if (el._isAdd) {
          hasAdd = true;
        }
      });
      return hasAdd;
    },
    addValue() {
      if (this.hasAdd()) {
        this.$message.warning('正在新增');
        return;
      }
      let params = {};
      if (this.defaultParams) {
        params = { ...this.defaultParams };
      }
      this.listSetting.forEach(i => {
        if (i.default || i.default === 0) {
          params[i.keyword] = i.default;
        }
      });
      // 判断是否新增
      params._isAdd = true;
      this.accountListData.unshift(params);
    },
    deleteItem(item, index) {
      this.$confirm('是否确定删除？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        this.accountListDelet(item.id);
      });
    },
    // 编辑
    editItem(item) {
      this.$set(item, '_isEdit', true);
    },
    // 保存
    save(item) {
      const saveData = JSON.parse(JSON.stringify(item));
      saveData.type = this.type;
      if (!saveData.payName || !saveData.payNum) {
        this.$message.error('请填写收款户名和收款账号');
        return;
      }
      saveData.supplierId = this.supplierId;
      if (item._isAdd) {
        delete saveData._isAdd;
        // 新增的话传的id是供应商id
        this.accountListAdd(saveData, item);
      } else {
        delete saveData._isEdit;
        // 编辑的话传的id是收款id
        saveData.id = item.id;
        this.accountListEdit(saveData, item);
      }
    },
    // 取消
    beCancle(item, index) {
      if (item._isAdd) {
        this.accountListData.splice(index, 1);
      } else {
        this.$set(item, '_isEdit', false);
        this.getAccountList(false, true);
      }
    },
    // 选择城市
    threeLevelArea(data, item, key) {
      item[key] = data.join(',');
    },
    handelArr(data) {
      if (!data) return [];
      if (typeof data === 'string') {
        return data.split(',');
      } else {
        return data;
      }
    },
    /**
     * 操作
     */
    accountListEdit(data, item) {
      accountEdit(data).then((res) => {
        this.getAccountList();
        if (res.code !== 200) {
          this.$message.error(res.message);
        } else {
          this.$set(item, '_isEdit', false);
          this.getAccountList();
        }
      });
    },
    accountListAdd(data, item) {
      accountAdd(data).then((res) => {
        if (res.code !== 200) {
          this.$message.error(res.message);
        } else {
          this.$set(item, '_isAdd', false);
          this.getAccountList();
        }
      });
    },
    accountListDelet(id) {
      const params = {
        id
      };
      params.type = this.type;
      // this.supplierId
      accountDelete(id, params).then((res) => {
        if (res.code === 200) {
          this.getAccountList();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 账户列表
    getAccountList(reset = false, muted = false) {
      if (reset) this.page = 1;
      const params = {
        type: this.type,
        perPage: this.perPage,
        page: this.page,
        id: this.supplierId,
        supplierId: this.supplierId
      };
      if (!muted) this.loading = true;
      accountList(params).then((res) => {
        this.loading = false;
        this.accountData = res.data;
        this.accountListData = res.data.items;
      }).catch((err) => {
        this.loading = false;
        console.error(err);
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getAccountList(true);
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getAccountList();
    }
  }
};
</script>
<style lang="scss">
.dynamic-order-cascader-popper-class {
  &::v-deep {
    .el-input {
      width: 250px;
    }
    .el-cascader-panel .el-cascader-menu__wrap {
      height: unset !important;
    }
  }
}
</style>
<style lang="scss" scoped>
.read-content {
  display: flex;
  .overflow {
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.line{
    width: 0px;
    height: 14px;
    border: 1px solid #DDDDDD;
    margin: 0 9px;
}
.custom-column {
  background-color: #f5f7fa;
  height: 56px;
  cursor: not-allowed;
  padding-left: 15px;
  padding-right: 15px;
  display: flex;
  align-items: center;
}
.add-btn {
  width: 100%;
  height: 56px;
  border: 1px dashed #406EFF;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  color: #406EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.unit {
  position: absolute;
  top: 50%;
  right: 5px;
  transform: translate(0, -50%);
}
.dynamic-container {
  margin-top: 15px;
  .dynamic-table-header {
    display:flex;align-items:center;
    .label {
      color: #141C3D;
      font-weight: 600;
    }
  }
  &::v-deep {
    .threee-level-area-wrap .el-input__inner {
      width: 100%;
    }
    .el-cascader-menu__wrap {
      height: unset !important;
      max-height: 204px !important;
    }
    .dynamic-edit-table-cell {
      background: #F9F9F9;
    }
    .el-table__fixed {
      &::before {
        background-color: transparent;
      }
    }
    .el-table__fixed-right {
      &::before {
        background-color: transparent;
      }
    }
    .el-table--border::after {
      background-color: transparent;
    }
    .el-table {
      border-color: transparent;
      &::before {
        background-color: transparent;
      }
      .el-table__body-wrapper {
        padding-bottom: 7px;
      }
      thead {
        th.dynamic-edit-table-cell {
          &:last-child {
            border-right-color: transparent;
          }
          &:nth-last-child(2) {
            border-right-color: transparent;
          }
        }
      }
      tbody {
        tr {
          td:last-child {
            border-right-color: transparent;
          }
        }
        .el-table__row {
          &:last-child {
            td {
              border-bottom: 1px solid #EBEEF5;
            }
          }
        }
      }
    }
    .el-date-table,.el-year-table,.el-month-table {
      th {
        border-right: none;
      }
    }
    .el-date-table td {
      padding: 4px 0 !important; border: none !important;
    }
    .el-year-table td {
      padding: 20px 3px !important; border: none !important;
    }
    .el-month-table td {
      padding: 8px 0 !important; border: none !important;
    }
  }
  &.editMode {
    &::v-deep {
      .el-select__caret {
        color: #333;
      }
      .el-table__row {
        td {
          padding: 0;
        }
        .cell {
          padding: 0;
          .el-input__inner {
            height: 56px;
            border-radius: 0;
            border-color: transparent;
          }
        }
      }
    }
  }
}
.select-inner {
  border: 1px solid transparent;
  height: 56px;
  display: flex;
  align-items: center;
}
.isSelect {
  &::v-deep {
    .el-input__inner {
      border-color: #406EFF !important;
    }
  }
  .select-inner {
    border-color: #406EFF !important;
  }
}
.isError {
  &::v-deep {
    .el-input__inner {
      border-color: red !important;
    }
    .attachment-container {
      border:1px solid red;
    }
  }
}
.attachment-container {
  width: 100%;
  height: 57px;
  display: flex;
  align-items: center;
  background-color: #fff;
}
</style>
